package com.th.cash.th2.product

import android.text.TextUtils
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.th.basemodel.base.BaseViewModel
import com.th.basemodel.ext.toast
import com.th.resmodel.databinding.FragmentBasicBinding
import kotlinx.coroutines.launch

class BasicFragment : VerifyBaseFragment<FragmentBasicBinding>() {

    override var type = 1

    private val mViewModel by viewModels<ProductVm>()

    override fun startObserve() {
        lifecycleScope.launch {
            mViewModel.uiState.collect {
                when (it) {
                    is ProductState.Idle -> {

                    }

                    is ProductState.BaseInfoData -> {
                        mDataList.clear()

                        if (it.data.MRZamUjLamppostNaUomFq.QylNBLMBombitaFwSlPhN.isNotEmpty()) {
                            mDataList.addAll(it.data.MRZamUjLamppostNaUomFq.QylNBLMBombitaFwSlPhN)
                        }

                        mBinding.rvFillBasicList.adapter?.notifyDataSetChanged()
                    }

                    is  ProductState.VerifySuccess ->{
                        nextPage(it.data.FqLBwdpDollarbirdSXQntyj.noneconomicSingle)
                    }

                    else -> {}
                }
            }
        }
    }

    override fun init() {
        mBinding.header.headTitle.text = "ข้อมูลพื้นฐาน"

        initVerifyAdapter(mBinding.rvFillBasicList)
        initClick()

        mViewModel.intentChannel.trySend(ProductIntent.InitBaseInfo(BaseInfoRequest(getPid())))
    }

    override fun onLazyInitData() {

    }

    override fun getVm(): BaseViewModel {
        return mViewModel
    }

    companion object {
        fun newInstance(): BasicFragment {
            return BasicFragment()
        }
    }

    private fun initClick() {
        mBinding.header.headBack.setOnClickListener {
            back(1)
        }

        mBinding.tvFillBaseSubmit.setOnClickListener {
            val params = mutableListOf<Pair<String, Any?>>()

            mDataList.forEach {
                if (it.DEaiqpxElectrodiagnosisXYIQybx == 0 && TextUtils.isEmpty(it.PxGEecSAntiwarMrDXISc.PxGEecSAntiwarMrDXISc)) {
                    toast("กรุณากรอกรายการรับรองให้ครบถ้วน")
                    return@setOnClickListener
                }

                params.add(
                    Pair(
                        it.RAEdwRPQuaveringlyMOIghzQ.sQDRQmIUnexactingIeHvoQV,
                        it.PxGEecSAntiwarMrDXISc.PxGEecSAntiwarMrDXISc
                    )
                )
            }

            mViewModel.intentChannel.trySend(
                ProductIntent.SaveBaseInfo(
                    BaseSaveRequest(
                        getPid(),
                        params
                    )
                )
            )
        }
    }
}